import { AfterViewInit, Component, OnInit, TemplateRef, ViewChild } from '@angular/core';
import { UserDto } from 'src/app/models/sys/user.dto';
import { ApiService } from 'src/app/services/api.service';
import { FormBuilder, FormControl, UntypedFormGroup, Validators } from '@angular/forms';
import { UserQueryParam } from 'src/app/models/param/user-query.param';
import { Consts } from 'src/app/consts/consts';
import { NzTableQueryParams } from 'ng-zorro-antd/table';
import { BehaviorSubject } from 'rxjs';
import { UserPassword } from 'src/app/models/bo/user-password';
import { NzMessageService } from 'ng-zorro-antd/message';
import { EditMode } from 'src/app/models/enums/edit-mode.enum';
import { NzModalComponent, NzModalService } from 'ng-zorro-antd/modal';
import { ContentHeaderService } from 'src/app/services/content-header.service';

@Component({
  selector: 'app-employee',
  templateUrl: './employee.component.html',
  styleUrl: './employee.component.less'
})
export class EmployeeComponent implements OnInit, AfterViewInit {
  @ViewChild('editModal') editModalRef!: NzModalComponent;

  // 搜索表单
  searchForm!: UntypedFormGroup;
  submitted = false;

  // 左侧选中部门
  selectedDeptId?: number;

  users: UserDto[] = [];
  pageIndex = 1;
  pageSize = 12;
  total = 0;

  // Modal
  modeSubject = new BehaviorSubject<{ mode: EditMode, user?: UserDto }>({ mode: EditMode.ADD, user: undefined });
  
  // 对话框title
  editTitle?: string;
  userName?: string;

  // 详情
  userSubject = new BehaviorSubject<UserDto>(new UserDto());

  assignRoleSubject = new BehaviorSubject<UserDto>(new UserDto());
  resetSubject = new BehaviorSubject<UserDto>(new UserDto());

  constructor(private _api: ApiService,
    private _fb: FormBuilder,
    private _message: NzMessageService,
    private _modal: NzModalService,
    private _contentHeader: ContentHeaderService) { }

  ngAfterViewInit(): void {
    setTimeout(() => {
      this._contentHeader.header.next('员工管理');
    });
  }

  ngOnInit(): void {
    console.log('Employee OnInit');

    this.onCreateForm();
    this.onSearch();
  }

  onCreateForm() {
    this.searchForm = this._fb.group({
      username: new FormControl('', [Validators.minLength(1), Validators.maxLength(20)]),
      phoneNumber: new FormControl('', [Validators.minLength(11), Validators.maxLength(11)]),
      enabled: new FormControl('')
    });
  }

  onSearch() {
    this.submitted = true;
    if (!this.searchForm.valid) {
      return;
    }

    this.resetPage();
    this.doSearch();
  }

  doSearch() {
    console.log('Employee OnSearch')
    const param = new UserQueryParam();
    param.pageNum = this.pageIndex;
    param.pageSize = this.pageSize;
    param.username = this.searchForm.get('username')?.value;
    param.phoneNumber = this.searchForm.get('phoneNumber')?.value;
    param.enabled = this.searchForm.get('enabled')?.value;
    param.deptId = this.selectedDeptId;

    this._api.getUserList(param).subscribe((resp) => {
      if (resp.code == Consts.RESP_OK) {
        console.log(`get user list ${resp.total}: ${resp.data}`);
        this.users = resp.data ?? [];
        this.total = resp.total;

        this.submitted = false;
      } 
    });
  }

  get fm() {
    return this.searchForm.controls;
  }

  onCreate(tplTitle: TemplateRef<object>, tplContent: TemplateRef<object>) {
    this.editTitle = '创建员工';
    this.userName = undefined;
    this.resetModal();

    this._modal.create({
      nzTitle: tplTitle,
      nzContent: tplContent,
      nzFooter: null,
      nzMaskClosable: false,
      nzClosable: false,
      nzWidth: 800,
      nzOnOk: () => {
        console.log(' added');
      }
    });

    this.modeSubject.next({ mode: EditMode.ADD, user: undefined });
  }

  onUpdate(tplTitle: TemplateRef<object>, tplContent: TemplateRef<object>, user: UserDto) {
    this.editTitle = '编辑员工';
    this.userName = user.username;
    this.resetModal();

    this._modal.create({
      nzTitle: tplTitle,
      nzContent: tplContent,
      nzFooter: null,
      nzMaskClosable: false,
      nzClosable: false,
      nzWidth: 800,
      nzOnOk: () => {
        console.log(' updated');
      }
    });

    this.modeSubject.next({ mode: EditMode.EDIT, user: user });
  }

  onDetail(tplTitle: TemplateRef<object>, tplContent: TemplateRef<object>, user: UserDto) {
    this.editTitle = '员工详情';

    this._modal.create({
      nzTitle: tplTitle,
      nzContent: tplContent,
      nzFooter: null,
      nzMaskClosable: false,
      nzClosable: false,
      nzWidth: 800,
      nzOnOk: () => {
        console.log('groupType detail');
      }
    });

    this.userSubject.next(user);
  }

  onAssignRoles(tplTitle: TemplateRef<object>, tplContent: TemplateRef<object>, user: UserDto) {
    this.editTitle = '分配角色';

    this._modal.create({
      nzTitle: tplTitle,
      nzContent: tplContent,
      nzFooter: null,
      nzMaskClosable: false,
      nzClosable: false,
      nzWidth: 800,
      nzOnOk: () => {
        console.log('role assign detail');
      }
    });

    this.assignRoleSubject.next(user);
  }

  onDelete(userId: number) {
    this._api.deleteUser(userId).subscribe((resp) => {
      if (resp.code == Consts.RESP_OK) {
        this._message.info("删除用户成功");
        this.onSearch();
      } else {
        this._message.warning("删除用户失败");
      }
    });
  }

  onReset() {
    this.searchForm.get('username')?.setValue(undefined);
    this.searchForm.get('phoneNumber')?.setValue(undefined);
    this.searchForm.get('enabled')?.setValue(undefined);
  }

  resetModal() {
    this.editTitle = '添加员工';
  }

  onResetPassword(tplTitle: TemplateRef<object>, tplContent: TemplateRef<object>, user: UserDto) {
    console.log('OnReset password');

    this._modal.create({
      nzTitle: "重置密码",
      nzContent: tplContent,
      nzFooter: null,
      nzMaskClosable: false,
      nzClosable: false,
      nzWidth: 480,
      nzOnOk: () => {
        console.log('password reset');
      }
    });

    this.resetSubject.next(user);
  }


  onResetEvent(result?: UserPassword) {
    console.log(`onResetEvent with result ${result}`);
    if (result != null) {
      this._api.resetUserPassword(result).subscribe((resp) => {
        if (resp.code == Consts.RESP_OK) {
          this._message.info("Reset password OK");
        } else {
          this._message.info("Reset password Error");
        }
      });
    }
    this._modal.closeAll();
  }

  onAssignRoleEvent(result: boolean) {
    console.log(`onAssignEvent with result ${result}`);

    if (result) {
      this.onSearch();
    }

    this._modal.closeAll();
  }

  onPageParamChange(params: NzTableQueryParams) {
    if (!this.searchForm.valid) {
      return;
    }
    
    this.pageIndex = params.pageIndex;
    this.pageSize = params.pageSize;
    this.doSearch();
  }

  onAddEmployeeEvent(result: boolean) {
    console.log(`add dept result ${result}`);
    this.resetModal();
    this._modal.closeAll();
    if (result) {
      this.onSearch();
    }
  }

  onDeptSelect(id: number) {
    console.log(`onDeptSelect with ${id}`);
    this.selectedDeptId = id;
    this.onSearch();
  }

  resetPage() {
    this.pageIndex = 1;
    this.pageSize = 10;
  }

  onDetailEvent(result: boolean) {
    this._modal.closeAll();
    console.log(`${result}`);
  }
}
